package com.atguigu.tingshu.user.service.strategy.impl;

import com.atguigu.tingshu.album.AlbumFeignClient;
import com.atguigu.tingshu.model.album.TrackInfo;
import com.atguigu.tingshu.model.user.UserPaidTrack;
import com.atguigu.tingshu.user.mapper.UserPaidTrackMapper;
import com.atguigu.tingshu.user.service.strategy.PaidRecordStrategy;
import com.atguigu.tingshu.vo.user.UserPaidRecordVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.units.qual.C;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * ClassName: TrackPaidRecordStrategy
 * Package: com.atguigu.tingshu.user.service.strategy.impl
 * Description:
 *
 * @Author 咚咚小圆帽
 * @Create 2025/8/4 Monday 17:41
 * @Version 1.0
 */
@Slf4j
@Component("1002")
public class TrackPaidRecordStrategy implements PaidRecordStrategy {

    @Autowired
    private UserPaidTrackMapper userPaidTrackMapper;

    @Autowired
    private AlbumFeignClient albumFeignClient;

    /**
     * 处理声音的发货逻辑
     *
     * @param userPaidRecordVo
     */
    @Override
    public void handlerPaidRecord(UserPaidRecordVo userPaidRecordVo) {
        log.info("[用户服务]处理声音发货逻辑");
        //2.处理虚拟物品发货-声音
        //2.1 根据订单编号查询已购声音表判断是否处理过该笔订单
        LambdaQueryWrapper<UserPaidTrack> userPaidTrackLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userPaidTrackLambdaQueryWrapper.eq(UserPaidTrack::getOrderNo, userPaidRecordVo.getOrderNo());
        Long count = userPaidTrackMapper.selectCount(userPaidTrackLambdaQueryWrapper);
        if (count > 0) {
            return;
        }

        //2.2 如果没有则新增用户购买声音记录
        List<Long> itemIdList = userPaidRecordVo.getItemIdList();
        Long trackId = itemIdList.get(0);
        TrackInfo trackInfo = albumFeignClient.getTrackInfo(trackId).getData();
        for (Long paidTrackId : itemIdList) {
            UserPaidTrack userPaidTrack = new UserPaidTrack();
            userPaidTrack.setOrderNo(userPaidRecordVo.getOrderNo());
            userPaidTrack.setUserId(userPaidRecordVo.getUserId());
            //需要根据声音id来查询专辑id
            Long albumId = trackInfo.getAlbumId();
            userPaidTrack.setAlbumId(albumId);
            //这里是需要处理每一个声音id，而不是刚开始取的trackId，那是我们列表中取的第一个声音id
            userPaidTrack.setTrackId(paidTrackId);

            userPaidTrackMapper.insert(userPaidTrack);

        }
    }
}
